<?php

class AnsModel extends Model {
	public $table = '360_ans';
	// 提交答案
	public function Answer(){
		// 问题id
		$aid = $_GET['aid'];
		$_POST['ans_time'] = time();
		$_POST['ans_uid'] = $_SESSION['id'];
		return $this->insert($_POST);
	}
	// 获取答案
	public function getAnswer($askId){
		$Sql = "SELECT ans_id,ask_id,
		ans_content,uid,account,ans_time FROM 360_ans AS ans
		JOIN 360_user AS user 
		ON ans.ans_uid = user.uid
		WHERE ask_id = {$askId}
		";
		return $this->query($Sql);
	}
	// 已采纳的答案
	public function accept($aid){
		$Sql = "SELECT * FROM
		360_ask AS ask
		INNER JOIN 360_ans AS ans ON ask.ask_id = ans.ask_id
		INNER JOIN 360_accept AS accept ON ask.ask_id = accept.ask_id
		WHERE ask.ask_id= {$aid}
		GROUP BY ask.ask_id;";
		return $this->query($Sql);
	}
	// 待解决问题
	public function noAccept(){
		$Sql = "SELECT
		ask.ask_id,
		state,
		COUNT(*) AS count,
		ask.ask_content,ask.ask_gold,
		ask.ask_time,
		ans.ans_content
		FROM
		360_ask AS ask
		LEFT JOIN 360_ans AS ans ON ask.ask_id = ans.ask_id
		WHERE state=0
		GROUP BY ask.ask_id  ORDER BY ask.ask_gold DESC";
		return $this->query($Sql);
	}

	public function Acceopts($aid){
		
		// 获取问题相关的记录
		$AskSql = "SELECT * FROM 360_ask WHERE ask_id = {$aid['askid']} ";
		$AskInfo = $this->query($AskSql);
		$AskInfo = current($AskInfo);
		// 获取答案相关的信息
		$AnsSql = "SELECT * FROM 360_ans WHERE ans_id = {$aid['ansid']} ";
		$AnsInfo = $this->query($AnsSql);
		$AnsInfo = current($AnsInfo);
		// 把问题的状态改成已解决
		$AskState = "UPDATE 360_ask SET state = 1 WHERE ask_id = {$aid['askid']} ";
		if(!$this->exe($AskState)){
			$Msg = array('state'=>0,'msg'=>'错误信息_1');
			echo json_encode($Msg);
			return false;
		}
		// 更新答案被采纳的用户的金币
		$AcceptUser = "UPDATE 360_user SET golds=golds+{$AskInfo['ask_gold']},suffer=suffer+5 WHERE uid = {$AnsInfo['ans_uid']}";
		if(!$this->exe($AcceptUser)){
			$Msg = array('state'=>0,'msg'=>'错误信息_2');
			echo json_encode($Msg);
			return false;
		}
		$A = new Model('360_accept');
		$AcceptInfo = array('ask_id'=>$aid['askid'],'ans_id'=>$aid['ansid'],'times'=>time());
		if(!$A->insert($AcceptInfo)){
			$Msg = array('state'=>0,'msg'=>'添加采纳是出现问题');
			echo json_encode($Msg);
			return false;
		}else{
			$Msg = array('state'=>1,'msg'=>'成功采纳');
			echo json_encode($Msg);
		}

	}

	public function checkAid(){
		$db = new Model("360_ask");
		$aid = isset($_GET['aid'])?$_GET['aid']:0;
		$Field = $db->where("ask_id = $aid")->find();
		if(empty($Field)){
			header("Location: index.php");
		}
	}
}

?>